package com.itshops.service.impl;

import com.itshops.dao.CartDao;
import com.itshops.dao.ProductDao;
import com.itshops.dao.impl.CartDapImpl;
import com.itshops.dao.impl.ProductDaoImpl;
import com.itshops.entity.Cart;
import com.itshops.entity.Product;
import com.itshops.service.CartService;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

public class CartserviceImpl implements CartService {
    CartDao cartDao=new CartDapImpl();
    @Override
    public void createCart(Integer uId, String pId) throws SQLException, InvocationTargetException, IllegalAccessException {
        //判断是否已经存在
        Cart cart =cartDao.hasCart(uId,pId);
        System.out.println(cart);
        if (cart != null) {
            //购物车已经存在,修改购物车
            cart.setCnum(cart.getCnum()+1);
            cartDao.updateCart(cart);
        }else {
            //没有存在则新创建
            //根据商品id查询
            ProductDao productDao =new ProductDaoImpl();
            Product product = productDao.selectProductByPid(pId);

            cart = new Cart();
            cart.setCnum(1);
            cart.setPid(Integer.parseInt(pId));
            cart.setProduct(product);
            cart.setUid(uId);

            cartDao.insertCart(cart);
        }
    }

    @Override
    public List<Cart> findAll(Integer uId) throws SQLException, InvocationTargetException, IllegalAccessException {

        List<Cart> carts=cartDao.selectCartsByUid(uId);
        return carts;
    }

    @Override
    public void deletecartByCid(String cid) throws SQLException {
        cartDao.deleteCartByCid(cid);
    }

    @Override
    public void updateCartByCid(String cid, String price, String cnum) throws SQLException {
        BigDecimal bigDecimal = new BigDecimal(cnum);
        BigDecimal pricebig = new BigDecimal(price);
        //计算小计
        BigDecimal count = bigDecimal.multiply(pricebig);
        cartDao.updateByCid(count,bigDecimal,cid);

    }

    @Override
    public void clearCart(String uid) throws SQLException {
        cartDao.deleteCarByUid(uid);
    }
}
